/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package core;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import logging.LOG;
import protocol.TSFile;

/**
 *
 * @author Jorge
 */
public class WriteThread extends Thread{

    private ThreadPool pool;
    private TSFile file;

    public WriteThread(ThreadPool pool) {
        this.pool = pool;
    }



    public synchronized void run(){
        LOG.append(this.getName() +" está pronta");
        while(true){
            try{
                this.wait();
            }catch(InterruptedException exception){
                exception.printStackTrace();
                this.interrupted();
            }
            if(file == null){
                continue;
            }
            drainChannel(file);

            pool.returnWorker(this);
        }
    }

    public synchronized void setFile(TSFile file) {
        this.file = file;
        this.notify();
    }


    

    private void drainChannel(TSFile file) {
        FileLock fileLock=null;
        try {


            FileOutputStream channel = file.getFileOutputStream();

             fileLock= channel.getChannel().lock();

            List<byte[]> buffers = file.removeBuffer();
            pool.testFile(file);
            for(byte[] bs : buffers){
                channel.write(bs);
            }
            
            if(file.getFileTag().getFileSize()==new Long(channel.getChannel().size()).intValue()){
                file.getCallback().onResult(null);
            }
            fileLock.release();

        } catch (IOException ex) {
            //não conseguiu fazer lock
        }finally{
            if(fileLock!=null)
                try {
                fileLock.release();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
       
    }


}
